from selenium import webdriver
from selenium.webdriver.support import expected_conditions as EC
import time
import random
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from PIL import Image
from ShowapiRequest import ShowapiRequest

#
driver = webdriver.Chrome()
driver.get('http://www.5itest.cn/register')


# 判断页面是否正确打开
# print(EC.title_contains('注册'))


# 判断元素是否存在
# locator = (By.CLASS_NAME,'controls')
# WebDriverWait(driver,2).until(EC.visibility_of_element_located(locator))

#获取属性的值
# email_element = driver.find_element_by_id('register_email')
# print(email_element.get_attribute('placeholder'))
# email_element.send_keys('wyu0430@163.com')
# print(email_element.get_attribute('value'))

# 生成输入的值
# for i in range(5):
#     user_email = ''.join(random.sample('123456789abcdedg',5)) + '@163.com'
#     print(user_email)
#
driver.save_screenshot('e:/code.png')
code_element = driver.find_element_by_id('getcode_num')
# 获取验证码的坐标值
print(code_element.location)
# # 计算整个验证码框的坐标值
left = code_element.location['x']
top = code_element.location['y']
right = code_element.size['width'] + left
height = code_element.size['height'] + top

# 在页面截图中裁剪验证码图,截图的分辨率与图片保存的分辨率不一致可能造成截图失败，

#获取窗口可视范围的width和height
html = driver.find_element_by_tag_name("html")


#设置图片重新打开的width和height
resize_width = html.size['width']
resize_height = html.size['height']

#resize图片
im = Image.open('e:/code.png')
resize_img = im.resize((resize_width, resize_height), Image.BILINEAR)


# 截取图片
img = resize_img.crop((left, top, right, height))
img.save('e:/code1.png')

# 读取验证码图片内容
r = ShowapiRequest("http://route.showapi.com/184-4","62626","d61950be50dc4dbd9969f741b8e730f5" )
r.addBodyPara("typeId", "35")
r.addBodyPara("convert_to_jpg", "0")
r.addBodyPara("needMorePrecise", "0")
r.addFilePara("image", r"E:/code1.png") #文件上传时设置
res = r.post()
text = res.json()['showapi_res_body']['Result']
print(text) # 返回信息
driver.find_element_by_id('captcha_code').send_keys(text)
time.sleep(5)


#定位元素
# driver.find_element_by_id('register_email').send_keys('wyu0430@163.oom')
# driver.find_element_by_id('register_nickname').send_keys('wyu0430')
# driver.find_element_by_name('password').send_keys('123456')
# driver.find_element_by_xpath('//*[@id="captcha_code"]').send_keys('111')
# time.sleep(5)
driver.close()